/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software 
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "GuiRender.h"
#include <D3D11.h>

#include "../Managers/DX11Manager.h"
#include "../Directors/DX11Director.h"

#include "../Content/BlendState.h"
#include "../Content/RasterizerState.h"
#include "../Content/SamplerState.h"
#include "../Components/GuiRectangle.h"

namespace Hogshead
{
	namespace DX11Rendering
	{
		ProcessCPP(Hogshead::DX11Rendering::GuiRender)

		int guiComparison(IComponent* in_first, IComponent* in_second)
		{
		
			/*if(in_first->getRenderInfo()->as<DX11GuiRectangleInfo>()->_texture->getKey() >
				in_first->getRenderInfo()->as<DX11GuiRectangleInfo>()->_texture->getKey())
			{
				return 1;
			}
			else if(in_first->getRenderInfo()->as<DX11GuiRectangleInfo>()->_texture->getKey() <
				in_first->getRenderInfo()->as<DX11GuiRectangleInfo>()->_texture->getKey())
			{
				return -1;
			}*/
			
			return 0;
		}

		GuiRender::GuiRender(void)
		{
			_gui_rects_buffer = NULL;
			
		}


		void GuiRender::finalize()
		{
			if(_gui_rects_buffer)
				this->_gui_rects_buffer->Release();
		}

		GuiRender::~GuiRender(void)
		{
		}

		void GuiRender::render(Camera* in_active_camera)
		{
			//if(_registered_components.size() > 0)
			//{
			//	DX11Manager::setRenderTargets(1, &(*in_render_targets)[DX11Director::BACK_BUFFER]->first, DX11Manager::_depth_stencil_view);
			//	DX11Manager::setTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);
			//	//DX11Manager::setVertexBuffer(this->_gui_rects_buffer, sizeof(GuiRectVertex));
			//	DX11Manager::setShaders(_vs, _gs, _ps);
			//	DX11Manager::setInputLayout(_input_layout);

			//	int start_draw_index = 0;
			//	int num_objects =  _registered_components.size();
			//	bool keep_drawing = true;
			//	int cur_object_index = 0;
			//	while(cur_object_index < num_objects)
			//	{
			//	//	//DX11GuiRectangleInfo* cur_rect_info = _registered_components[cur_object_index]->getRenderInfo()->as<DX11GuiRectangleInfo>();
			//	//	Texture* cur_texture = cur_rect_info->_texture;
			//	//	RasterizerState* cur_rasterizer_state = cur_rect_info->_rasterizer_state;
			//	//	SamplerState* cur_sampler_state = cur_rect_info->_sampler_state;
			//	//	BlendState* cur_blend_state = cur_rect_info->_blend_state;

			//	//	Texture* next_texture = NULL;
			//	//	RasterizerState* next_rasterizer_state = NULL;
			//	//	SamplerState* next_sampler_state = NULL;
			//	//	BlendState* next_blend_state = NULL;

			//	//	start_draw_index = cur_object_index;
			//	//	for(int i = cur_object_index; i < num_objects && keep_drawing; )
			//	//	{
			//	//		//start_draw_index = i;
			//	//		if(i+1 >= num_objects)
			//	//		{
			//	//			cur_object_index += i + 1;
			//	//			break;
			//	//		}
			//	//		i++;
			//	//	
			//	//		next_rasterizer_state = _registered_components[cur_object_index]->getRenderInfo()->as<DX11GuiRectangleInfo>()->_rasterizer_state;
			//	//		next_sampler_state = _registered_components[cur_object_index]->getRenderInfo()->as<DX11GuiRectangleInfo>()->_sampler_state;
			//	//		next_blend_state = _registered_components[cur_object_index]->getRenderInfo()->as<DX11GuiRectangleInfo>()->_blend_state;
			//	//		next_texture = _registered_components[i]->getRenderInfo()->as<DX11GuiRectangleInfo>()->_texture;

			//	//		if(cur_texture->getKey() != next_texture->getKey() || cur_rasterizer_state->getKey() != next_rasterizer_state->getKey() 
			//	//			|| cur_sampler_state->getKey() != next_sampler_state->getKey() || cur_blend_state != next_blend_state)
			//	//		{
			//	//			cur_object_index += i;
			//	//			break;
			//	//		}
			//	//	}
			//	//
			//	//	if(next_rasterizer_state == NULL || cur_rasterizer_state->getKey() != next_rasterizer_state->getKey())
			//	//	{
			//	//		DX11Manager::setRasterizerState(cur_rasterizer_state->_rasterizer_state);
			//	//	}
			//	//	
			//	//	if(next_blend_state == NULL || cur_blend_state->getKey() != next_blend_state->getKey())
			//	//	{
			//	//		DX11Manager::setBlendState(cur_blend_state->_blend_state, NULL, 4294967295);
			//	//	}

			//	//	if(next_sampler_state == NULL || cur_sampler_state->getKey() != next_sampler_state->getKey())
			//	//	{
			//	//		DX11Manager::setSamplers(0, 1, &cur_sampler_state->_sampler_state, cur_sampler_state->_shader_type);
			//	//	}

			//	//	if(next_texture == NULL || cur_texture->getKey() != next_texture->getKey())
			//	//	{
			//	//		DX11Manager::setPSShaderResource(0, &cur_texture->_shader_resource_view);
			//	//	}

			//	//	DX11Manager::draw(cur_object_index - start_draw_index, start_draw_index);
			//	}
			//}
		}

		void GuiRender::initialize()
		{
			_buffer_size = START_NUM_GUI_OBJECTS;
			createVertexBuffer(_buffer_size);
			this->_enabled = true;
		}

		void GuiRender::createVertexBuffer(UINT in_num_vertices)
		{
			//sort our components by texture
			//_registered_components.sort(&guiComparison);
			
			/*for(int i = 0; i < _registered_components.size(); i++)
			{
				_vertices_vector.add(_registered_components[i]->getRenderInfo()->as<DX11GuiRectangleInfo>()->_vertex);
				_textures.add(_registered_components[i]->getRenderInfo()->as<DX11GuiRectangleInfo>()->_texture);
			}

			if(_registered_components.size() != 0)
			{
				_vs = ((GuiRectangle*)_registered_components[0])->_vs->_vs;
				_input_layout =  ((GuiRectangle*)_registered_components[0])->_vs->_input_layout;
				_ps = ((GuiRectangle*)_registered_components[0])->_ps->_ps;
				_gs = ((GuiRectangle*)_registered_components[0])->_gs->_gs;
			

				D3D11_BUFFER_DESC bd;
				ZeroMemory(&bd, sizeof(bd));
				bd.Usage = D3D11_USAGE_DEFAULT;
				bd.ByteWidth = sizeof(GuiRectVertex) * (in_num_vertices);
				bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
				bd.CPUAccessFlags = 0;
				D3D11_SUBRESOURCE_DATA InitData;
				ZeroMemory(&InitData, sizeof(InitData));
				InitData.pSysMem = (const GuiRectVertex*)(_vertices_vector);

				DX11Manager::createBuffer(&bd, &InitData, &_gui_rects_buffer);
#ifdef _DEBUG
				const char debug_string[] = "gui rects buffer vertex buffer";
				HRESULT hr = _gui_rects_buffer->SetPrivateData( WKPDID_D3DDebugObjectName, sizeof(debug_string) - 1, debug_string );
				if(FAILED(hr))
				{
					StringBuilder sb;
					sb << "ERROR ON CONTENT LOAD: gui rects vertex buffer could not be named";
					DX11Manager::_logger->write(sb);
					throw new Exception(sb);
				}
#endif
				*/
			}
		
	
		void GuiRender::registerComponent(IComponent* in_component)
		{
			
			if(in_component->is<GuiRectangle>())
			{
				_registered_components.add(in_component);
				//if our vertex buffer is NULL then this object will be added when it is initialized
				if(_gui_rects_buffer != NULL)
				{
					
					if(_registered_components.size() < _buffer_size)
					{
						//sort our components by texture
						_registered_components.sort(&guiComparison);
						//DX11Manager::updateSubresource(_gui_rects_buffer, (const GuiRectVertex*)(_vertices_vector), sizeof(GuiRectVertex));
					}
					else
					{
						_buffer_size += GUI_INCREMENT_SIZE;
						createVertexBuffer(_buffer_size);
					}
				}
			}
		}
	}

}